<template>
  <div v-if="visible" class="poster">
    <div class="popup">
      <div class="poster-warp">
        <div id="recommend-poster1">
          <img
            :src="`${shareObj.mainPic}?x-oss-process=image/resize,m_mfit,w_750`"
            class="bgUrl poster-img"
            alt=""
          />
          <div class="poster-content">
            <div class="content">
              <div class="shop-wrap">
                <div class="left-box">
                  <div class="shop-info">
                    <div class="shop-logo">
                      <img
                        :src="
                          (shareObj.forwarder &&
                            shareObj.forwarder.forwarderShopLogoUrl) ||
                            defaultImg
                        "
                        alt=""
                      />
                    </div>
                    <div class="shop-desc">
                      <span>{{
                        (shareObj.forwarder &&
                          shareObj.forwarder.forwarderMessage) ||
                          '' | sliceHandle(20)
                      }}</span>
                      <span
                        >{{
                          (shareObj.forwarder &&
                            shareObj.forwarder.forwarderShopName) ||
                            '' | sliceHandle(8)
                        }}
                      </span>
                      <span>{{
                        (shareObj.forwarder &&
                          shareObj.forwarder.forwardShopDesc) ||
                          ''
                      }}</span>
                    </div>
                  </div>
                  <div class="shop-meta">
                    <span v-for="(it, idx) in shareObj.tagList" :key="idx">
                      <i>
                        <img src="../../assets/logo.png" alt="" />
                      </i>
                      <em>{{ it }}</em>
                    </span>
                  </div>
                </div>
                <div class="shop-link">
                  <img class="qrcode poster-img" :src="qrcode" />
                  <div class="qrcode-tip">
                    <span>长按图片识别二维码</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="isShow" class="posterUrl">
      <div v-if="!posterUrl" class="loading-poster">
        <div class="loading-content"></div>
      </div>
      <img
        v-if="getHostEnvironment() === 'wechat' && posterUrl"
        :src="posterUrl"
        class="posterimg no-select"
        alt=""
      />
      <div
        v-if="getHostEnvironment() === 'browser' && posterUrl"
        class="posterimg"
      >
        <span>长按图片，保存至手机，方便分享和再次浏览 </span>
        <img :src="posterUrl" />
      </div>
      <img
        v-if="posterUrl"
        src="@/assets/close-btn.png"
        class="close-btn"
        alt="点击关闭"
        @click="close"
      />
    </div>
    <div class="poster-bg"></div>
  </div>
</template>
<script>
import QRCode from 'qrcode';
import html2canvas from '@/utils/html2canvas.esm';
import { getScrollY, getHostEnvironment } from '@/utils/util';
import lock from '@/utils/lock';
import shareCardMixin from '@/mixins/shareCardMixin';
import defaultImg from '@/assets/logo.png';

export default {
  filters: {
    sliceHandle(value = '', length) {
      if (!value) {
        return '';
      }
      const arr = [...value];
      if (arr.length > length) {
        return arr.slice(0, length).join('') + '...';
      }
      return value;
    }
  },
  mixins: [shareCardMixin],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    shareObj: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isShow: true,
      posterUrl: null,
      qrcode: null,
      defaultImg,
      timeId: null,
      retryTotal: 0,
      maxRetryTotal: 20 // 最大重试次数
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.loadAllImg();
      } else {
        this.popupClose();
        this.posterUrl = '';
        lock.beforeClose();
      }
    }
  },
  beforeDestroy() {
    this.initData();
  },
  deactivated() {
    this.initData();
  },
  beforeRouteLeave() {
    this.initData();
  },
  methods: {
    getHostEnvironment,
    close() {
      this.$emit('update:visible', false);
    },
    /* img加载工具方法 */
    loadImg(url) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = url;
        img.onload = () => {
          img.onload = null;
          resolve();
        };
        img.onerror = () => {
          console.error('pic加载失败===', url);
          const err = new Error('加载失败');
          reject(err);
        };
      });
    },
    // 第一步: 保证图片loading
    async loadAllImg() {
      this.resetZoom();
      const { mainPic, forwarder } = this.shareObj;
      const needLoadImgList = [mainPic, forwarder.forwarderShopLogoUrl];
      const imgsLoadArrays = needLoadImgList.map(item => this.loadImg(item));
      this.$nextTick(() => {
        Promise.all(imgsLoadArrays)
          .then(() => {
            this.createPoster();
          })
          .catch(err => {
            console.log(err);
            this.$toast('海报加载失败，请稍后重试！');
            this.close();
            // this.createPoster();
          });
      });
    },
    // 第二步: 海报生成
    async createPoster() {
      QRCode.toDataURL(this.shareObj.link).then(res => {
        this.qrcode = res;
        this.$nextTick(() => {
          try {
            clearInterval(this.timeId);
            this.timeId = setInterval(() => {
              this.retryTotal += 1;
              if (this.retryTotal >= this.maxRetryTotal) {
                clearInterval(this.timeId);
                this.retryTotal = 0;
              } else if (this.completeHandle()) {
                clearInterval(this.timeId);
                this.retryTotal = 0;
                this.createImg();
              }
            }, 200);
          } catch (err) {
            clearInterval(this.timeId);
            console.error(err);
            this.$toast('海报加载失败，请稍后重试！');
            this.close();
          }
          // this.createImg();
        });
      });
    },
    // 图片生成
    createImg() {
      const source = document.getElementById('recommend-poster1');
      if (!source) {
        return;
      }
      const rect = source.getBoundingClientRect();
      const coptDom = source.cloneNode(true);
      coptDom.style.zIndex = -1;
      coptDom.style.width = `${rect.width}px`;
      coptDom.style.height = `${rect.height}px`;
      document.body.appendChild(coptDom);
      const scrollY = getScrollY(); // 适配iOS 13, 12 及以下 && 安卓
      console.log(rect, scrollY);
      html2canvas(coptDom, {
        allowTaint: true,
        useCORS: true,
        x: rect.left,
        y: rect.top + scrollY,
        // canvas绘制页面时会根据全局页面的滚动情况自动向下偏移。当然了，scrollX也是一样的道理。
        // scrollY: 0, // 截图的元素正是fixed定位的, 所以截图渲染的时候元素在画布上相对Y轴偏移了滚动条的高度, 使用scrollY对这个偏移进行修正
        scale: 3,
        backgroundColor: 'transparent'
      })
        .then(canvas => {
          const imgUri = canvas.toDataURL();
          document.body.removeChild(coptDom);
          lock.afterOpen();
          this.posterUrl = imgUri;
        })
        .catch(err => {
          console.log(err);
          document.body.removeChild(coptDom);
          this.$toast('海报加载失败，请稍后重试！');
          this.close();
        });
    },
    completeHandle() {
      const div = document.getElementById('recommend-poster1');
      if (!div) {
        return false;
      }

      const imgArr = div.querySelectorAll('.poster-img') || [];
      return Array.prototype.slice
        .call(imgArr)
        .every(img => img.complete && img.naturalWidth);
    },
    initData() {
      clearInterval(this.timeId);
      this.timeId = null;
      this.retryTotal = 0;
      this.maxRetryTotal = 20;
    }
  }
};
</script>
<style lang="scss" scoped>
@keyframes mymove {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: transparent;
  z-index: 9999;
  width: 100%;
  max-height: 100%;
  overflow-y: auto;
  transition: 0.3s ease-out;
  transform: translate3d(-50%, -50%, 0);
}
.loading-poster {
  width: 273px;
  height: 456px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding-left: 135px;
  .loading-content {
    width: 20px;
    height: 20px;
    border-radius: 20px;
    border-right: 1px solid #c3cbd6;
    animation: mymove 1s linear infinite;
    -webkit-animation: mymove 1s linear infinite;
  }
}
.poster-warp {
  width: 300px;
}
.posterUrl {
  top: 50%;
  left: 50%;
  position: fixed;
  // width: 273px;
  transform: translate(-50%, -50%);
  z-index: 99999;
  border-radius: 8px;
  .posterimg {
    width: 300px;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    span {
      color: #ffffff;
      font-size: 12px;
      margin-bottom: 8px;
    }
    &.no-select {
      -webkit-touch-callout: none; /*系统默认菜单被禁用*/
      user-select: none; //文本不能被选择
    }
    img {
      border-radius: 8px;
      width: 100%;
    }
  }
  .close-btn {
    width: 30px;
    height: 30px;
    position: relative;
    left: 50%;
    margin-left: -15px;
    margin-top: 30px;
  }
}
.poster-bg {
  width: 100%;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99998;
  background-color: rgba(0, 0, 0, 0.7);
}
#recommend-poster1 {
  // height: 575px;
  font-family: PingFang-SC-Medium;
  width: 375px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  overflow: hidden;
  .bgUrl {
    width: 100%;
  }
  .poster-content {
    position: absolute;
    left: 0;
    top: 50px;
    width: 100%;
    height: 100%;
    overflow: hidden;
    .content {
      color: #fff;
      background-color: #fff;
      width: 100%;
      position: absolute;
      // top: 374px;
      bottom: 50px;
      box-sizing: border-box;
      padding: 20px;
      height: 143px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .shop-wrap {
        width: 100%;
        display: flex;
        justify-content: space-between;
        .left-box {
          display: flex;
          flex: 1;
          flex-direction: column;
          justify-content: inherit;
          padding-top: 11px;
          .shop-info {
            display: flex;
            align-items: center;
            .shop-logo {
              width: 60px;
              height: 60px;
              overflow: hidden;
              border-radius: 60px;
              box-sizing: border-box;
              img {
                width: 60px;
                height: 60px;
                border-radius: 60px;
                object-fit: cover;
              }
            }
            .shop-desc {
              display: flex;
              max-width: 144px;
              flex-direction: column;
              color: rgba(102, 102, 102, 1);
              padding-left: 8px;
              // margin-top:-10px;
              font-size: 12px;
              span {
                line-height: 16px;
                &:nth-child(2) {
                  padding: 3px 0 6px;
                  font-weight: 600;
                  font-size: 14px;
                  color: rgba(51, 51, 51, 1);
                }
                &:nth-child(3) {
                  line-height: 12px;
                }
              }
            }
          }
          .shop-meta {
            font-size: 10px;
            color: rgba(102, 102, 102, 1);
            display: flex;
            span {
              position: relative;
              padding-right: 10px;
              display: flex;
              i {
                width: 12px;
                height: 12px;
                margin-right: 5px;
                &:last-child {
                  margin: 0;
                }
                img {
                  width: 100%;
                }
              }
              em {
                font-style: normal;
              }
            }
          }
        }
        .shop-link {
          display: flex;
          // flex: 1;
          flex-direction: column;
          align-items: center;
          justify-content: inherit;
          min-width: 90px;
          // img{
          //   margin-top:10px;
          // }
          .qrcode {
            width: 80px;
            height: 80px;
          }
          .qrcode-tip {
            padding-top: 9px;
            font-size: 10px;
            color: rgba(102, 102, 102, 1);
            line-height: 14px;
          }
        }
      }
    }
  }
}
</style>
